package controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.io.FilenameUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import pojo.AppCategory;
import pojo.AppInfo;
import pojo.DataDictionary;
import pojo.DevUser;
import service.AppInfoService;
import service.CategoryService;
import service.DataService;
import service.DevUserService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("/dev")
public class DevUserController {
    @Resource
    private DevUserService devUserService;
    @Resource
    private CategoryService categoryService;
    @Resource
    private DataService dataService;
    @Resource
    private AppInfoService appInfoService;

    @RequestMapping("/toLogin")
    public String toLogin(){
        return "devlogin";
    }

    //登录
    @RequestMapping("/login")
    public String login(HttpSession session, @RequestParam String devCode,@RequestParam String devPassword){
        DevUser devUser = devUserService.devLogin(devCode,devPassword);
        if (devUser!=null){
            session.setAttribute("devUserSession",devUser);
            return "redirect:/dev/toMain";
        } else {
            throw new RuntimeException("用户名或密码不正确");
        }
    }

    @RequestMapping("/toMain")
    public String toMain(){
        return "/developer/main";
    }

    //注销
    @RequestMapping("/logout")
    public String logout(HttpSession session){
        session.invalidate();
        return "redirect:/index.jsp";
    }

    //app信息列表
    @RequestMapping("/flatform/app/list")
    public String appList(@RequestParam(defaultValue = "1") Integer pageIndex, String querySoftwareName, Integer queryStatus,Integer queryFlatformId,
                          Integer queryCategoryLevel1, Integer queryCategoryLevel2, Integer queryCategoryLevel3, Model model, HttpSession session){
        PageHelper.startPage(pageIndex,5);
        List<AppInfo> appList = appInfoService.selList(querySoftwareName,queryStatus,queryCategoryLevel1,queryCategoryLevel2,queryCategoryLevel3,queryFlatformId);
        PageInfo pages = new PageInfo(appList);
        List appInfoList = pages.getList();
        model.addAttribute("pages",pages);
        List<DataDictionary> flatFormList = dataService.ddList("APP_FLATFORM");
        List<DataDictionary> statusList = dataService.ddList("PUBLISH_STATUS");
        List<AppCategory> categoryLevel1List = categoryService.cateList(0);
        model.addAttribute("appInfoList",appInfoList);
        model.addAttribute("flatFormList",flatFormList);
        model.addAttribute("statusList",statusList);
        model.addAttribute("categoryLevel1List",categoryLevel1List);
        session.setAttribute("querySoftwareName",querySoftwareName);
        session.setAttribute("queryFlatformId",queryFlatformId);
        session.setAttribute("queryStatus",queryStatus);
        session.setAttribute("queryCategoryLevel1",0);
        session.setAttribute("queryCategoryLevel2",queryCategoryLevel2);
        session.setAttribute("queryCategoryLevel3",queryCategoryLevel3);
        return "/developer/appinfolist";
    }

    @RequestMapping("/flatform/app/appinfoadd")
    public String toAdd(){
        return "/developer/appinfoadd";
    }

    //新增app基础信息
    @PostMapping("/flatform/addsave")
    public String add(AppInfo appInfo, HttpSession session, HttpServletRequest request,
                      @RequestParam(value = "a_logoPicPath",required = false) MultipartFile a_logoPicPath){
        String logoPicPath = null;
        String logoLocPath = null;
        if(!a_logoPicPath.isEmpty()){
            String path = request.getSession().getServletContext().getRealPath("statics"+File.separator+"uploadfiles");
            String originalFile = a_logoPicPath.getOriginalFilename();
            String prefix = FilenameUtils.getExtension(originalFile);
            int fileSize = 10000000;
            if (a_logoPicPath.getSize()>fileSize){
                request.setAttribute("fileUploadError","上传大小不能超过10MB");
                return "/developer/appinfoadd";
            }else if (prefix.equalsIgnoreCase("jpg")||prefix.equalsIgnoreCase("png")||prefix.equalsIgnoreCase("gif")) {
                String fileName = UUID.randomUUID() + "." + prefix; //新的文件名
                File targetFile = new File(path);
                if(!targetFile.exists()){
                    targetFile.mkdirs();
                }
                try{
                    a_logoPicPath.transferTo(new File(targetFile,fileName));
                }catch (Exception e){
                    e.printStackTrace();
                    request.setAttribute("fileUploadError","上传失败！");
                    return "/developer/appinfoadd";
                }
                logoPicPath = File.separator+"BeyoundPlatform"+ File.separator+"statics"+File.separator+"uploadfiles"+File.separator+fileName;
                logoLocPath = path + File.separator+ fileName;
            }else {
                request.setAttribute("fileUploadError","图片格式不正确");
                return "/developer/appinfoadd";
            }
        }
        appInfo.setLogoPicPath(logoPicPath);
        appInfo.setLogoLocPath(logoLocPath);
        if (appInfoService.add(appInfo)>0){
            return "redirect:/dev/flatform/app/list";
        }
        return "redirect:/developer/appinfoadd";
    }

    //进入修改app基础信息页面
    @RequestMapping("/flatform/app/view")
    public String view(Integer id,Model model){
        AppInfo appInfo = appInfoService.view(id);
        model.addAttribute("appInfo",appInfo);
        return "/developer/appinfomodify";
    }

    //修改app基础信息
    @RequestMapping("/save")
    public String save(AppInfo appInfo, HttpSession session, HttpServletRequest request,
                       @RequestParam(value = "attach",required = false) MultipartFile attach){
        String logoPicPath = null;
        String logoLocPath = null;
        if(!attach.isEmpty()){
            String path = request.getSession().getServletContext().getRealPath("statics"+File.separator+"uploadfiles");
            String originalFile = attach.getOriginalFilename();
            String prefix = FilenameUtils.getExtension(originalFile);
            int fileSize = 10000000;
            if (attach.getSize()>fileSize){
                request.setAttribute("fileUploadError","上传大小不能超过10MB");
                return "/developer/appinfomodify";
            }else if (prefix.equalsIgnoreCase("jpg")||prefix.equalsIgnoreCase("png")||prefix.equalsIgnoreCase("gif")) {
                String fileName = UUID.randomUUID() + "." + prefix; //新的文件名
                File targetFile = new File(path);
                if(!targetFile.exists()){
                    targetFile.mkdirs();
                }
                try{
                    attach.transferTo(new File(targetFile,fileName));
                }catch (Exception e){
                    e.printStackTrace();
                    request.setAttribute("fileUploadError","上传失败！");
                    return "/developer/appinfomodify";
                }
                logoPicPath = File.separator+"BeyoundPlatform"+ File.separator+"statics"+File.separator+"uploadfiles"+File.separator+fileName;
                logoLocPath = path + File.separator+ fileName;
            }else {
                request.setAttribute("fileUploadError","图片格式不正确");
                return "/developer/appinfomodify";
            }
        }
        appInfo.setLogoPicPath(logoPicPath);
        appInfo.setLogoLocPath(logoLocPath);
        if (appInfoService.update(appInfo)>0){
            return "redirect:/dev/flatform/app/list";
        }
        return "redirect:/developer/appinfomodify";
    }

    //删除图片
    @RequestMapping("/del")
    @ResponseBody
    public String del(int id){
        HashMap<String,String> map = new HashMap<>();
        AppInfo appInfo = appInfoService.view(id);
        String LogoLocPath = appInfo.getLogoLocPath();
        File file = new File(LogoLocPath);
        if (file.delete()){
            map.put("result","success");
        }else {
            map.put("result","failed");
        }
        return JSON.toJSONString(map);
    }

    //上架
    @RequestMapping("/onSale/{appId}")
    @ResponseBody
    public Object onSale(@PathVariable Integer appId){
        HashMap<String,String> map = new HashMap<>();
        AppInfo appInfo = appInfoService.view(appId);
        map.put("errorCode","0");
        if(appInfo.getStatus() == 2 || appInfo.getStatus() ==5){
            if (appInfoService.onSale(4,appId)>0){
                map.put("resultMsg","success");
            }else {
                map.put("resultMsg","failed");
            }
        }else if(appInfo.getStatus()==4){
            if (appInfoService.onSale(5,appId)>0){
                map.put("resultMsg","success");
            }else {
                map.put("resultMsg","failed");
            }
        } else {
            map.put("resultMsg","failed");
        }
        return JSON.toJSONString(map);
    }
}
